﻿using DotNetOpenAuth.OAuth2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace OAuthResourceServerWebApi.Core
{
    public class OAuth2Handler : DelegatingHandler
    {
        private static async Task<IPrincipal> VerifyOAuth2(HttpRequestMessage httpDetails, params string[] requiredScopes)
        {
            // for this sample where the auth server and resource server are the same site,
            // we use the same public/private key.
            using (var signing = WebApiApplication.CreateAuthorizationServerSigningServiceProvider())
            {
                using (var encrypting = WebApiApplication.CreateResourceServerEncryptionServiceProvider())
                {
                    var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting));
                    return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes);
                }
            }
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //var httpDetails = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            //var requestUri = request.RequestUri;
            var scope = request.RequestUri.AbsolutePath;

            var principal = VerifyOAuth2(request, scope);

            try
            {
                if (principal.Result != null)
                {
                    HttpContext.Current.User = principal.Result;
                    Thread.CurrentPrincipal = principal.Result;
                }

                return base.SendAsync(request, cancellationToken);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
    }
}